package com.qbw.app.module.mine.activity;

import android.widget.Toast;

import androidx.annotation.NonNull;

import com.qbw.app.R;
import com.st.BlueNRG.fwUpgrade.BlueNRGAdvertiseFilter;
import com.st.BlueNRG.fwUpgrade.feature.BlueNRGOTASupport;
import com.st.BlueSTSDK.Features.standardCharacteristics.StdCharToFeatureMap;
import com.st.BlueSTSDK.Node;
import com.st.BlueSTSDK.Utils.BLENodeDefines;
import com.st.BlueSTSDK.Utils.ConnectionOption;
import com.st.BlueSTSDK.Utils.advertise.AdvertiseFilter;
import com.st.BlueSTSDK.gui.DemosActivity;
import com.st.STM32WB.fwUpgrade.FwUpgradeSTM32WBActivity;
import com.st.STM32WB.fwUpgrade.feature.STM32OTASupport;
import com.st.STM32WB.p2pDemo.Peer2PeerDemoConfiguration;

import java.util.List;

public class FwUpgradeActivity extends com.st.BlueSTSDK.gui.NodeListActivity {


    @Override
    public void onNodeSelected(@NonNull Node n) {
        ConnectionOption.ConnectionOptionBuilder optionsBuilder = ConnectionOption.builder()
                .resetCache(clearCacheIsSelected())
                .enableAutoConnect(keepConnectionOpenIsSelected())
                //.enableAutoConnect(false)
                .setFeatureMap(STM32OTASupport.getOTAFeatures())
                .setFeatureMap(BlueNRGOTASupport.getOTAFeatures())
                .setFeatureMap(new StdCharToFeatureMap());

        if (Peer2PeerDemoConfiguration.isValidDeviceNode(n)) {
            optionsBuilder.setFeatureMap(Peer2PeerDemoConfiguration.getCharacteristicMapping());
        }

        ConnectionOption options = optionsBuilder.build();

        //disable the ble server for sensor tile box, to improve stability for the fw upgrade.
        // it is not clear why.. and probably is not the root cause
        if (n.getType() != Node.Type.SENSOR_TILE_BOX) {
            try {
                n.enableNodeServer(BLENodeDefines.FeatureCharacteristics.getDefaultExportedFeature());
            } catch (IllegalStateException e) {
                Toast.makeText(this, "Bluetooth server not started", Toast.LENGTH_SHORT).show();
            }
        }


        if (n.getAdvertiseInfo() instanceof BlueNRGAdvertiseFilter.BlueNRGAdvertiseInfo)
            startActivity(com.st.BlueSTSDK.gui.fwUpgrade.FwUpgradeActivity.getStartIntent(this, n, false, options));
            finish();
    }

    @Override
    public boolean displayNode(@NonNull Node n) {
        return true;
    }

    @Override
    protected List<AdvertiseFilter> buildAdvertiseFilter() {
        List<AdvertiseFilter> defaultList =  super.buildAdvertiseFilter();
        defaultList.add(new BlueNRGAdvertiseFilter());
        return defaultList;
    }
}
